
import static junit.framework.Assert.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.events.EventFiringWebDriver;

public class SeleniumWebDriverExamples extends SeleniumBase {
	
	@Test
	  public void shouldPressArrowDownKey() throws InterruptedException {
	    // given
	    open("http://allegro.pl");

	    WebElement searchBox = insertText(By.id("string"), "Samsu");
	    TimeUnit.SECONDS.sleep(1);

	    // when
	    searchBox.sendKeys(Keys.ARROW_DOWN, Keys.ARROW_DOWN, Keys.ENTER);
	  }

	  @Test
	  public void shouldNavigateForwardBackward() {
	    // given
	    open("http://gazeta.pl");
	    open("http://onet.pl");

	    // when
	    driver.navigate().back();
	    driver.navigate().forward();
	    driver.navigate().refresh();
	  }

	  @Test
	  public void shouldVerifyAllPagesFromMenuExists_ObjectOrientedWay() {
	    // given
	    open("http://code.google.com/p/selenium/");

	    // when
	    List<WebElement> meni = driver.findElements(By.xpath("//html/body/div[2]/a"));
	    List<String> urls = new LinkedList<String>();

	    for (WebElement webElement : meni) {
	      urls.add(webElement.getAttribute("href").toString());
	    }
	    for (String url : urls) {
	      open(url);
	    }
	  }

	  @Test
	  public void shouldVerifyAllPagesFromMenuExists_XPathWay() throws Exception {
	    // given
	    open("http://code.google.com/p/selenium/");

	    // when
	    int elementId = 1;
	    while (isElementPresent(By.xpath("//html/body/div[2]/a[" + elementId + "]"))) {
	      click(By.xpath("//html/body/div[2]/a[" + elementId + "]"));
	      elementId++;
	    }
	  }

	  @Test
	  public void shouldAcceptAlert() throws InterruptedException {
	    open("http://www.iopus.com/imacros/demo/v5/dialogs/javascript.htm");
	    click(By.xpath("//table[2]/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[2]/td/div/table/tbody/tr[2]/td[2]/b/input"));

	    // zamkniecie alertu
	    Alert alert = driver.switchTo().alert();
	    assertEquals("Popup 1", alert.getText());
	    alert.accept();

	    // wybranie opcji zmiany koloru
	    click(By.xpath("//table[2]/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[2]/td/div/table/tbody/tr[4]/td[2]/b/input"));
	    Alert confirm = driver.switchTo().alert();
	    confirm.accept();

	    // TimeUnit.SECONDS.wait(5);
	  }

	  @Test
	  public void shoudlManageCookies() {
	    open("http://www.iopus.com/imacros/demo/v6/dialogs/html/");
	    printCookies("Before modifications");

	    Cookie cookie = new Cookie("myName", "Marcin");

	    // dodanie ciasteczka
	    driver.manage().addCookie(cookie);
	    printCookies("After modification");

	    // usuniecie ciasteczka
	    driver.manage().deleteCookie(cookie); // also by name
	    printCookies("After delete");

	    // usuniecie wszystkich ciasteczek
	    driver.manage().deleteAllCookies();
	    printCookies("Non cookie left");
	  }

	  private void printCookies(String caption) {
	    System.out.println(caption);

	    Set<Cookie> cookies = driver.manage().getCookies();
	    for (Cookie cookie : cookies) {
	      System.out.println("cookie -> " + cookie);
	    }
	  }

	  @Test
	  public void shouldModifyFirefoxProfile() {
	    FirefoxProfile profile = new FirefoxProfile();
	    profile.setAcceptUntrustedCertificates(true);

	    // tak mozemy stworzyc webdriver log fine
	    profile.setPreference("webdriver.log.file", "/home/marcin/test_automation_selenium/selenium.log");

	    WebDriver profiledDriver = new FirefoxDriver(profile);
	    profiledDriver.get("http://onet.pl");

	    profiledDriver.quit();
	  }

	  @Test
	  public void shouldTakeScreenShotAfterTestFail() {
	    open("http://onet.pl");

	    if (driver instanceof TakesScreenshot) {
	      byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
	      String fileName = "screen_" + Calendar.getInstance().getTimeInMillis() + ".png";

	      try {
	        FileOutputStream fos = new FileOutputStream("C:\\" + fileName);
	        fos.write(bytes);
	        fos.close();
	      } catch (Exception e) {
	        e.printStackTrace();
	      }
	    }
	  }

	  @Test
	  public void shouldExecuteJavaScript() throws InterruptedException {
	    open("http://onet.pl");

	    FirefoxDriver fdriver = (FirefoxDriver) driver;
	    fdriver.executeScript("window.scrollTo(0, document.body.scrollHeight);");

	    TimeUnit.SECONDS.sleep(1);
	  }

	  @Test
	  public void shouldMoveBetweenFrames() throws InterruptedException {
	    open("http://www.iopus.com/imacros/demo/v4/frames/index.htm");

	    driver.switchTo().frame("main3");
	    insertText(By.name("T1"), "some text");

	    driver.switchTo().defaultContent(); // powrot do korzenia drzewa DOM

	    driver.switchTo().frame("main2");
	    insertText(By.name("T1"), "some text");

	    TimeUnit.SECONDS.sleep(1);
	  }

	  @Test
	  public void shouldMoveElementsBetweenLists() throws InterruptedException {
	    open("http://developer.yahoo.com/yui/examples/dragdrop/dd-reorder_clean.html");

	    WebElement element = driver.findElement(By.id("li1_1"));
	    WebElement target = driver.findElement(By.id("ul2"));

	    // tradycyjne wykorzystanie drag and drop
	    Actions actions = new Actions(driver);
	    actions.dragAndDrop(element, target).perform();

	    // alternatywne wykorzystanie Actions do budowania lancucha wywolan
	    WebElement element2 = driver.findElement(By.id("li1_2"));

	    Action dragAndDrop = actions.clickAndHold(element2).moveToElement(target).release(element2).build();

	    dragAndDrop.perform();
	  }

	  @Test
	  public void shouldUploadFile() {
	    open("http://www.iopus.com/imacros/demo/v4/file-upload.htm");

	    WebElement element = driver.findElement(By.id("uploaded_file"));
	    element.sendKeys("C:\\Users\\marcin\\Desktop\\Oferta szkolenie.odt");
	  }

	  @Test
	  public void shouldDownloadFile() throws InterruptedException {
	    String fileName = "selenium-2.15.0.tar.gz";
	    String dir = "C://";
	   
	    FirefoxProfile profile = new FirefoxProfile();
	    profile.setPreference("browser.download.folderList", 2);
	    profile.setPreference("browser.download.manager.showWhenStarting", false);
	    profile.setPreference("browser.download.dir", dir);
	    profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");

	    WebDriver profiledDriver = new FirefoxDriver(profile);
	    profiledDriver.get("http://pypi.python.org/pypi/selenium");

	    WebElement link = profiledDriver.findElement(By.linkText(fileName));
	    link.click();

	    // lepiej wykorzystac aktywne oczekiwanie
	    TimeUnit.SECONDS.sleep(60);

	    // i jeszcze weryfikacja czy plik sie faktycznie pobral
	    File file = new File(dir + fileName);
	    assertTrue("File doesn't exists " + dir + fileName, file.exists());

	    profiledDriver.quit();
	  }

	  @Test
	  public void shouldLogEvents() { 
	    EventFiringWebDriver eventFiringDriver = new EventFiringWebDriver(driver);
	    eventFiringDriver.register(new LoggingEventListener()); // simply implement this class to enable logging

	    eventFiringDriver.get("http://www.google.pl/");

	    WebElement searchField = eventFiringDriver.findElement(By.id("lst-ib"));
	    searchField.sendKeys("selenium");
	    searchField.submit();
	  }


}
